#include "setlicencedialog.h"
#include "ui_setlicencedialog.h"
#include "../share/global.h"
#include "mainwindow.h"

#include <QMessageBox>

#define MAGIC1 1250925678L
#define MAGIC2 5820281L

SetLicenceDialog::SetLicenceDialog(QWidget *parent) :
    days(0),
    QDialog(parent),
    ui(new Ui::SetLicenceDialog)
{
    ui->setupUi(this);

    ui->userIdEdit->setText(QString("%1").arg(generateUserId(), 8, 16, QChar('0')).toUpper());
    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(onOk()));
}

SetLicenceDialog::~SetLicenceDialog()
{
    delete ui;
}

void SetLicenceDialog::onOk()
{
    uint uid = ui->userIdEdit->text().toUInt(0, 16);
    quint64 licence = ui->licenceEdit->text().toULongLong(0, 16);

    quint32 temp2 = uid*MAGIC1+MAGIC2;
    qint32 temp1 = (licence>>16)^temp2;
    if ((qint32(licence)&0xFFFF) == ((temp1*MAGIC2)&0xFFFF)) {
        temp1 -= MAGIC2;
        if (temp1%17 == 0) {
            setDaysCount(temp1/17);
            accept();
        }
    } else {
        QMessageBox::critical(this, tr("Set New Licence"),
                              tr("Invalid Licence"));
    }
}

bool SetLicenceDialog::verifyExpireDate()
{
    static bool firstTip = true;
    int days = getDaysCount();
    int daysLeft = days - (MY_BIRTH.daysTo(QDate::currentDate()));
    if ((daysLeft<=15) && (daysLeft>=0) && firstTip) {
        QMessageBox::warning(const_cast<MainWindow*>(mainWindow), tr("Licence Expire"),
                             tr("Licence will be expired in %1 days.").arg(daysLeft));
        firstTip = false;
    } else if (daysLeft < 0) {
        SetLicenceDialog dialog(const_cast<MainWindow*>(mainWindow));
        return (dialog.exec()==QDialog::Accepted) && verifyExpireDate();
    }
    return true;
}
